package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.result.BaseContext;
import com.itheima.reggie.result.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求的uri
        String requestURI = request.getRequestURI();

        //2.判断本次请求是否需要处理
        //2.1定义不需要拦截的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        //2.2匹配成功直接放行
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url,requestURI);
            if (match) {
                filterChain.doFilter(request,response);
                //删除资源垃圾
                BaseContext.removeCurrentId();
                return;
            }
        }

        //3.1判断员工端登陆状态
        if (request.getSession().getAttribute("employee") != null) {
            Long empId = (Long) request.getSession().getAttribute("employee");
            //在同一线程中设置id
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            //删除资源垃圾
            BaseContext.removeCurrentId();
            return;
        }

        //3.2判断移动端登陆状态
        if (request.getSession().getAttribute("user") != null) {
            Long userId = (Long) request.getSession().getAttribute("user");
            //在同一线程中设置id
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            //删除资源垃圾
            BaseContext.removeCurrentId();
            return;
        }

        //4.未登录，响应前端数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //删除资源垃圾
        BaseContext.removeCurrentId();
        return;
    }
}
